package com.whty.demo.encrypt;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EncryptUtil {

	private static Logger logger = LoggerFactory.getLogger(EncryptUtil.class);
	
	/**
     * 给添加了Encrypt的属性加密
     * @param entity PO类
     * @param names
     * @param states
     */
    public static void encrypt(Object entity){
        List<Field> fieldList = ReflectUtil.getEncryptFileds(entity);
        
        for(Field field : fieldList){
        	
        	Method setterMethod = ReflectUtil.getSetter(field, entity);
            Method getterMethod = ReflectUtil.getGetter(field, entity);
            
            logger.info("field:"+field.getName());
            
            try{
                Object value = getterMethod.invoke(entity);
                
                if(value != null){
                	
                	logger.info("encrypt pre value:"+value);
                	
                    value = ReflectUtil.encrypt(field, entity);
                    
                    logger.info("encrypt finish value:"+value);
                    
                    setterMethod.invoke(entity, value);
                }
            }catch (IllegalAccessException e){
                e.printStackTrace();
            }catch (IllegalArgumentException e){
                e.printStackTrace();
            }catch (InvocationTargetException e){
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 给添加了Encrypt的属性解密
     * @param entity PO类
     * @param session
     */
	public static void decrypt(Object entity){
    	
        List<Field> fieldList = ReflectUtil.getEncryptFileds(entity);
        
        for(Field field : fieldList){            
            Method setterMethod = ReflectUtil.getSetter(field, entity);
            Method getterMethod = ReflectUtil.getGetter(field, entity);
            
            logger.info("field:"+field.getName());
            
            try{
                Object value = getterMethod.invoke(entity);
                
                if(value != null){
                	logger.info("decrypt pre value:"+value);
                    value = ReflectUtil.decrypt(field, entity);
                    logger.info("decrypt finish value:"+value);
                    setterMethod.invoke(entity, value);
                }
            }catch (IllegalAccessException e){
                e.printStackTrace();
            }catch (IllegalArgumentException e){
                e.printStackTrace();
            }catch (InvocationTargetException e){
                e.printStackTrace();
            }
        }
    }
	
}
